<template>
  <div>
    <form @submit.prevent="addMessage">
      <input v-model="newMessage.name" placeholder="你的名字" required />
      <textarea v-model="newMessage.body" placeholder="你的留言" required></textarea>
      <button type="submit">发送留言</button>
    </form>

    <div v-if="loading">加载留言中...</div>
    <ul v-else>
      <li v-for="msg in messages" :key="msg.id">
        <strong>{{ msg.name }}</strong>：{{ msg.body }}
        <button @click="deleteMessage(msg.id)">删除</button>
      </li>
    </ul>

    <div v-if="error" class="error">⚠️ {{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

// 数据区
const messages = ref([])
const newMessage = ref({ name: '', body: '' })
const loading = ref(false)
const error = ref('')

// 获取留言列表
const fetchMessages = async () => {
  loading.value = true
  error.value = ''
  try {
    const res = await axios.get('https://jsonplaceholder.typicode.com/comments?_limit=5')
    messages.value = res.data
  } catch (err) {
    error.value = '获取留言失败，请稍后再试。'
  } finally {
    loading.value = false
  }
}

// 添加留言
const addMessage = async () => {
  if (!newMessage.value.name || !newMessage.value.body) return
  try {
    const res = await axios.post('https://jsonplaceholder.typicode.com/comments', {
      name: newMessage.value.name,
      body: newMessage.value.body,
    })
    // 模拟添加
    messages.value.unshift({ ...res.data, id: Date.now() })
    newMessage.value = { name: '', body: '' }
  } catch (err) {
    error.value = '发送失败，请检查网络连接。'
  }
}

// 删除留言（本地模拟删除）
const deleteMessage = async (id) => {
  try {
    await axios.delete(`https://jsonplaceholder.typicode.com/comments/${id}`)
    messages.value = messages.value.filter(msg => msg.id !== id)
  } catch (err) {
    error.value = '删除失败，请稍后重试。'
  }
}

// 加载时请求一次
onMounted(() => {
  fetchMessages()
})
</script>

<style scoped>

</style>
